let sql = require('../sql/sql');
let data = require('../libs/data');
var db = require('../libs/db');
var Promsise = require('bluebird');
var client = require('redis').createClient();
var request = require('request');
Array.prototype.contains = function(val)
{
    for (var i = 0; i < this.length; i++)
    {
        if (this[i] == val)
        {
            return true;
        }
    }
    return false;
};
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
function getToken() {
    return new Promise(function(resolve, reject){
        client.get('szyx_token', function (err, object) {
            if (!err) {
                if(object != null){
                    console.log('缓存中数据：',object);
                    resolve(object);
                }else{
                    request({
                        url: 'https://api.convertlab.com/security/accesstoken?grant_type=client_credentials&appid=cl020b15e174c6423&secret=313cbd2810e53d7e7937610cee8b3bffd2fe6573',
                        method: "get",
                        headers: {
                            "Content-Type": "application/json;charset=utf-8",
                        },
                    }, function (error, response, body) {
                        console.log('新查数据：',body);
                        if(error){
                            reject(error);
                        }else{
                            let access_token = JSON.parse(body).access_token;
                            client.set('szyx_token', access_token, function (err) {
                                console.log(err)
                            });
                            client.expire('szyx_token', 7100);
                            resolve(access_token);
                        }
                    });
                }
            }
        });
    });
}

function getUserInfoByOpenid(openid,token){
    return new Promise(function(resolve, reject){
        request({
            url: 'https://api.convertlab.com/v1/customeridentities?access_token='+token+'&identityType=wechat&identityValue='+openid+'',
            method: "get",
            headers: {
                "Content-Type": "application/json;charset=utf-8",
            },
        }, function (error, response, body) {
            console.log('新查数据：',body);
            if(error){
                reject(error);
            }else{
                resolve(body);
            }
        });
    });
}
//5.推送注册事件
function registerEvent(customerId,token) {
    return new Promise(function(resolve, reject){
        let body = {
            "customerId": customerId,	//客户id，创建客户可获得
            "event": "c_pinjiuhui_register",
            "date": new Date().Format("yyyy-MM-ddThh:mm:ssZ"),	//固定时间格式
            "campaign": "PJH001",	//活动编码
            "campaignName": "品酒会"	//活动名称
        };
        request({
            url: 'https://api.convertlab.com/v1/customerevents?access_token='+token+'',
            method: "post",
            headers: {
                "Content-Type": "application/json;charset=utf-8",
            },
            body:JSON.stringify(body)
        }, function (error, response, body) {
            console.log('推送注册事件：',body);
            if(error){
                reject(error);
            }else{
                resolve(body);
            }
        });
    });
}
module.exports = {
    //使用微信openid查询客户
    getUserInfoByOpenid (req, res) {
        let openid = req.body.openid;
        (async()=>{
            let token = await getToken();
            request({
                url: 'https://api.convertlab.com/v1/customeridentities?access_token='+token+'&identityType=wechat&identityValue='+openid+'',
                method: "get",
                headers: {
                    "Content-Type": "application/json;charset=utf-8",
                },
            }, function (error, response, body) {
                console.log('2.使用微信openid查询客户：',body);
                data.code = '200';
                data.msg = body;
                res.status(200).send(JSON.stringify(data));
            });
        })();
    },
    //3.创建带身份的客户
    createUser (req, res) {
        let openid = req.body.openid;
        console.log('openid',openid);
        (async()=>{
            let token = await getToken();
            let userinfo = await getUserInfoByOpenid(openid,token);
            console.log('userinfo--',userinfo);
            if(JSON.parse(userinfo).length <= 0){
                var sql = 'select a.openid identityValue,a.nick identityName,b.username name,b.phone mobile,b.sex gender,b.boss attr1,CONCAT(b.prov,b.city,b.area) attr9 from jyj_user_wx a LEFT JOIN jyj_user b on a.userid = b.userid where a.openid = :openid';
                let info = await db.sequelize.query(sql, {
                    replacements: {openid: openid},
                    type: db.sequelize.QueryTypes.SELECT
                });
                console.log('info--',info);
                let user = info[0];
                let body = {
                    "customer": {
                        "name": user.name,	//姓名
                        "mobile" :user.mobile,	//手机号
                        "gender" : user.gender, // 性别，默认为0，男：1，女：2
                        "attr":{
                            "attr1":user.attr1=='0'?false:true,	//自定义字段，是否为终端店老板，是:true，否:false
                            "attr9":user.attr9	// 自定义字段，报名区域
                        }
                    },
                    "customerIdentities": [
                        {
                            "identityType": "wechat",	//微信身份类型
                            "identityValue": user.identityValue,	//微信openid
                            "identityName": user.identityName
                        }
                    ]
                }
                request({
                    url: 'https://api.convertlab.com/v1/customerandidentities?access_token='+token+'',
                    method: "post",
                    headers: {
                        "Content-Type": "application/json;charset=utf-8",
                    },
                    body: JSON.stringify(body)
                }, function (error, response, body) {
                    console.log('创建带身份的客户：',body);
                    data.code = '200';
                    data.msg = body;
                    res.status(200).send(JSON.stringify(data));
                });
            }else{
                var sql = 'select a.openid identityValue,a.nick identityName,b.username name,b.phone mobile,b.sex gender,b.boss attr1,CONCAT(b.prov,b.city,b.area) attr9 from jyj_user_wx a LEFT JOIN jyj_user b on a.userid = b.userid where a.openid = :openid';
                let info = await db.sequelize.query(sql, {
                    replacements: {openid: openid},
                    type: db.sequelize.QueryTypes.SELECT
                });
                console.log('info--',info);
                let user = info[0];
                let body = {
                    "name": user.name,	//姓名
                    "mobile" :user.mobile,	//手机号
                    "gender" : user.gender, // 性别，默认为0，男：1，女：2
                    "attr":{
                        "attr1":user.attr1=='0'?false:true,	//自定义字段，是否为终端店老板，是:true，否:false
                        "attr9":user.attr9	// 自定义字段，报名区域
                    }
                }
                request({
                    url: 'https://api.convertlab.com/v1/customers/'+JSON.parse(userinfo)[0].customerId+'?access_token='+token+'',
                    method: "put",
                    headers: {
                        "Content-Type": "application/json;charset=utf-8",
                    },
                    body: JSON.stringify(body)
                }, function (error, response, body) {
                    console.log('更新客户信息：',body);
                    data.code = '200';
                    data.msg = body;
                    res.status(200).send(JSON.stringify(data));
                });
            }
        })();
    },
    //3.第一轮创建带身份的客户
    createFirstUser (req, res) {
        let openid = req.body.openid;
        console.log('openid',openid);
        (async()=>{
            let token = await getToken();
            let userinfo = await getUserInfoByOpenid(openid,token);

            if(JSON.parse(userinfo).length <= 0){
                var sql = 'select a.openid identityValue,a.nick identityName,b.username name,b.phone mobile,b.sex gender,b.boss attr1,CONCAT(b.prov,b.city,b.area) attr9 from jyj_user_wx a LEFT JOIN jyj_user b on a.userid = b.userid where a.openid = :openid';
                let info = await db.sequelize.query(sql, {
                    replacements: {openid: openid},
                    type: db.sequelize.QueryTypes.SELECT
                });
                console.log('info--',info);
                let user = info[0];
                let body = {
                    "customer": {
                        "name": user.name,	//姓名
                        "mobile" :user.mobile,	//手机号
                        "gender" : user.gender, // 性别，默认为0，男：1，女：2
                        "attr":{
                            "attr1":user.attr1=='0'?false:true,	//自定义字段，是否为终端店老板，是:true，否:false
                            "attr9":user.attr9	// 自定义字段，报名区域
                        }
                    },
                    "customerIdentities": [
                        {
                            "identityType": "wechat",	//微信身份类型
                            "identityValue": user.identityValue,	//微信openid
                            "identityName": user.identityName
                        }
                    ]
                }
                request({
                    url: 'https://api.convertlab.com/v1/customerandidentities?access_token='+token+'',
                    method: "post",
                    headers: {
                        "Content-Type": "application/json;charset=utf-8",
                    },
                    body: JSON.stringify(body)
                }, function (error, response, body) {
                    console.log('创建带身份的客户：',body);
                    registerEvent(body.id,token);
                    data.code = '200';
                    data.msg = body;
                    res.status(200).send(JSON.stringify(data));
                });
            }else{
                var sql = 'select a.openid identityValue,a.nick identityName,b.username name,b.phone mobile,b.sex gender,b.boss attr1,CONCAT(b.prov,b.city,b.area) attr9 from jyj_user_wx a LEFT JOIN jyj_user b on a.userid = b.userid where a.openid = :openid';
                let info = await db.sequelize.query(sql, {
                    replacements: {openid: openid},
                    type: db.sequelize.QueryTypes.SELECT
                });
                console.log('info--',info);
                let user = info[0];
                let body = {
                    "name": user.name,	//姓名
                    "mobile" :user.mobile,	//手机号
                    "gender" : user.gender, // 性别，默认为0，男：1，女：2
                    "attr":{
                        "attr1":user.attr1=='0'?false:true,	//自定义字段，是否为终端店老板，是:true，否:false
                        "attr9":user.attr9	// 自定义字段，报名区域
                    }
                }
                request({
                    url: 'https://api.convertlab.com/v1/customers/'+JSON.parse(userinfo)[0].customerId+'?access_token='+token+'',
                    method: "put",
                    headers: {
                        "Content-Type": "application/json;charset=utf-8",
                    },
                    body: JSON.stringify(body)
                }, function (error, response, body) {
                    console.log('更新客户信息：',body);
                    registerEvent(JSON.parse(userinfo)[0].customerId,token);
                    data.code = '200';
                    data.msg = body;
                    res.status(200).send(JSON.stringify(data));
                });
            }
        })();
    },
    //更新客户自定义属性
    updateUser (req, res) {
        let openid = req.body.openid;
        let userid = req.body.userid;
        let codeid = req.body.codes;
        (async()=>{
            let token = await getToken();
            let userinfo = await getUserInfoByOpenid(openid,token);
            console.log('userinfo',userinfo);
            if(JSON.parse(userinfo).length > 0){

                var sql = 'SELECT a.totaltime,b.tag,CASE WHEN CONCAT( a.topic1, ",", a.topic2, ",", a.topic3 ) = a.okanswer THEN "1" ELSE "2" END isok FROM ( SELECT a.codeid, a.acid, a.id, a.topic1, a.topic2, a.topic3, a.totaltime, a.createtime, a.answer1, a.answer2, a.answer3, a.active, GROUP_CONCAT(a.okanswer ORDER BY a.id) okanswer FROM ( SELECT a.codeid, c.acid, b.id, a.topic1, a.topic2, a.topic3, a.totaltime, DATE_FORMAT(a.createtime, "%Y-%m-%d") createtime, b.okanswer, b.answer1, b.answer2, b.answer3, c.active FROM jyj_usertopic a, jyj_topic b, jyj_activity c WHERE a.codeid = b.codeid AND b.codeid = c.codeid AND a.userid = :userid AND a.codeid = :codeid ) a ) a LEFT JOIN jyj_ac b ON a.acid = b.acid';
                let info = await db.sequelize.query(sql, {
                    replacements: {userid: userid,codeid:codeid},
                    type: db.sequelize.QueryTypes.SELECT
                });
                let body = {
                    "attr":{
                        "attr10":info[0].isok=='1'?'答题正确':'答题不正确'
                    }
                };
                console.log(body);
                request({
                    url: 'https://api.convertlab.com/v1/customers/'+JSON.parse(userinfo)[0].customerId+'?access_token='+token+'',
                    method: "put",
                    headers: {
                        "Content-Type": "application/json;charset=utf-8",
                    },
                    body: JSON.stringify(body)
                }, function (error, response, body) {
                    let mbody = {
                        "customerId": JSON.parse(userinfo)[0].customerId,	//客户id，通过微信openid查询客户或创建客户可获得
                        "event": "c_pinjiuhui_takepart"+info[0].tag, //事件id见上方
                        "date": new Date().Format("yyyy-MM-ddThh:mm:ssZ"),	//固定时间格式
                        "campaign": "PJH001",	//活动编码
                        "campaignName": "品酒会",	//活动名称
                        "time": info[0].totaltime //答题时长	，单位为秒
                    };
                    console.log('更新客户自定义属性：',mbody);
                    request({
                        url: 'https://api.convertlab.com/v1/customerevents?access_token='+token+'',
                        method: "post",
                        headers: {
                            "Content-Type": "application/json;charset=utf-8",
                        },
                        body: JSON.stringify(mbody)
                    }, function (error, response, body) {
                        console.log('推送参加活动事件：',body);
                    });
                    data.code = '200';
                    data.msg = body;
                    res.status(200).send(JSON.stringify(data));
                });
            }
        })();
    },
    //推送参加活动事件
    joinEvent (req, res) {
        let openid = req.body.openid;
        let time = req.body.time;
        (async()=>{
            let token = await getToken();
            let userinfo = await getUserInfoByOpenid(openid,token);
            if(JSON.parse(userinfo).length > 0){
                let body = {
                        "customerId": JSON.parse(userinfo)[0].customerId,	//客户id，通过微信openid查询客户或创建客户可获得
                        "event": "c_pinjiuhui_takepart1", //事件id见上方
                        "date": new Date().Format("yyyy-MM-ddThh:mm:ssZ"),	//固定时间格式
                        "campaign": "PJH001",	//活动编码
                        "campaignName": "品酒会",	//活动名称
                        "time": time //答题时长	，单位为秒
                    };
                request({
                    url: 'https://api.convertlab.com/v1/customerevents?access_token='+token+'',
                    method: "post",
                    headers: {
                        "Content-Type": "application/json;charset=utf-8",
                    },
                    body: JSON.stringify(body)
                }, function (error, response, body) {
                    console.log('推送参加活动事件：',body);
                    data.code = '200';
                    data.msg = body;
                    res.status(200).send(JSON.stringify(data));
                });
            }
        })();
    },
};